class Solution {
    public int[][] generateMatrix(int n) {
        //模拟法，从外到内环绕数组填充数据
        //n x n方阵自外向内一共有不超过n/2层（单个中心元素不算一层）矩形框。
        int[][] matrix = new int[n][n];
        int times = 0;  //方框层数
        int count = 1;
        while(times <= (n >> 1)){
            int len = n - (times << 1);
            for(int i = 0; i < len - 1; i++){
                //一次循环填充当前框
                matrix[times][times + i] = count + i; //从左到右
                matrix[times + i][times + len - 1] = count + len - 1 + i;//从上到下
                matrix[times + len - 1][times + len - i - 1] = count + 2*(len - 1) + i;//从右到左
                matrix[times + len - i - 1][times] = count + 3*(len - 1) + i;//从下到上
            }
            times++;
            count += 4 * (len - 1);
        }
        //填充单个中心元素
        if(n % 2 != 0){
            matrix[n/2][n/2] = n * n;
        }
        return matrix;

    }
}